<template>
	<view>
		<!-- <u-search
			v-model="keyword"
			:show-action="false"
			@change="searchlist"
			placeholder="请输入关键字"
		></u-search> -->
		<u-button type="primary" @click="gotoconnect">添加连接</u-button>
		<u-list @scrolltolower="scrolltolower" v-if="linefiberlistBynode != false || status == 'loading'">
			<u-list-item v-for="(item, index) in linefiberlistBynode" :key="index">
				<u-cell :title="(index+1)+'、'+ item.Fiber.Name"
					:label=" ' 节点序号:'+ item.Idx + ' 皮长:' + item.Length +' 敷设类型:' + item.LayType" 
					>
					<view slot="right-icon">
						<u-button type="primary" @click.native.stop="toconnect(item)" >连接详情</u-button>
					</view>
				</u-cell>
				<view style="display: flex; justify-content:space-around">
					<u-button :customStyle="{width: '120px'}" v-if='choosenLine.indexOf(item.FiberId)==-1' @click='tochoose(item.FiberId)' type="success" size="mini">选中</u-button>
					<u-button :customStyle="{width: '120px'}" v-else @click='delchoose(item.FiberId)' type="error" size="mini">取消选中</u-button>
					<u-button :customStyle="{width: '120px'}" @click='tochange(item)' type="primary" size="mini">修改连接属性</u-button>
					<u-button :customStyle="{width: '120px'}" @click='toshowLine(item.FiberId)' type="primary" size="mini">详情</u-button>
				</view>
			</u-list-item>
			<u-loadmore :status="status" v-if="loading" />
		</u-list>
		<u-empty mode="data" icon="https://project.gxrunxiang.com/cdn/list.png" v-else>
		</u-empty>
		<u-popup :show="lineshow" @close="lineshow = false" :closeable='true'>
			<view style="margin-top:5px; font-weight: bold;">当前选中缆线与屏幕内可选缆线</view>
			<view style="margin-top:15px;">
				<u-sticky><u-button type="primary" :plain="true" @click="toaddfiber">创建缆线</u-button></u-sticky>
				<u-list height='460px' @scrolltolower="scrolltolowerLine">
					<u-list-item v-for="(item, index) in linefiberlist" :key="index">
						<u-cell :title='item.Name' @click="modalshow = true,FiberId = item.Id"
							:label="'类型:'+(item.Ftype ? item.Ftype : '')+' 创建者:'+(item.Creator.Name ? item.Creator.Name : '') + ' 芯数:'+(item.Num ? item.Num : '' )">
						<view slot="right-icon">
							<u-button type="error" @click.native.stop="del(item.Id)"
							v-if="item.Coordinate == null">删除</u-button>
						</view>
						</u-cell>
					</u-list-item>
					<u-loadmore :status="lineStatus" v-if="lineLoading" />
					<!-- <u-empty mode="data" icon="https://project.gxrunxiang.com/cdn/list.png" v-if="linefiberlist.length == 0 && lineLoading != 'loading'">
					</u-empty> -->
				</u-list>
			</view>
		</u-popup>
		<u-modal title="数据" :show="modalshow" @confirm="connect" :closeOnClickOverlay="true"
			@close="modalshow = false,length = '',laytype=''">
			<u--form labelWidth="auto" labelPosition="top" :rules="rules" ref="uForm" :model="addFormState">
				<u-form-item label="到该缆线起点的皮长(米)"  :required="true" prop="Length"><u-input v-model="addFormState.Length" placeholder="请输入到该缆线起点的皮长(米)" /></u-form-item>
				<u-form-item label="敷设方式" @click="addlaytypeshow = true"><u-input disabled
						v-model="laytype" /></u-form-item>
			</u--form>
		</u-modal>
		<u-modal title="更改或删除" :show="changeshow" @confirm="changeinfo" :closeOnClickOverlay="true"
			@close="changeshow = false">
			<u--form labelWidth="auto" labelPosition="top" :rules="rules" ref="uForm1" :model="formState">
				<u-button type="error" @click="delconnect" style="display: block;">删除连接</u-button>
				<u-form-item label="节点序号"><u-input v-model="formState.Idx" /></u-form-item>
				<u-form-item label="到该缆线起点的皮长(米)"  :required="true" prop="Length"><u-input v-model="formState.Length" placeholder="请输入到该缆线起点的皮长(米)" type="number"/></u-form-item>
				<u-form-item label="敷设方式" @click="laytypeshow = true"><u-input disabled
						v-model="formState.LayType" /></u-form-item>
			</u--form>
		</u-modal>
		<u-action-sheet :show="laytypeshow" :actions="columns" title="请选择类型" @close="laytypeshow = false"
			@select="changelaytype">
		</u-action-sheet>
		<u-action-sheet :show="addlaytypeshow" :actions="columns" title="请选择类型" @close="addlaytypeshow = false"
			@select="tochangelaytype">
		</u-action-sheet>
		<u-toast ref="uToast" style="z-index: 999;"></u-toast>
	</view>
</template>

<script>
	import {
		getlinefibernode,
		getlinefiber,
		addFiberNode,
		delFiberNode,
		fiberNodeUpdate,
		deleteLinefiber
	} from '@/common/api.js'
	import coordtransform from 'coordtransform'
	export default {
		data() {
			return {
				linefiberlistBynode: [],
				linefiberlist: [],
				choosenLine: [],
				keyword: "",
				pageIndex: 1, //当前页数
				pageSize: 20, //页数大小
				linePageIndex: 1,
				linePageSize: 50,
				lineTotalPage: "",
				lineTotal: 0,
				totalPage: "", //总页数
				total: 0, //数据总数
				status: 'loadmore', //加载状态
				lineStatus: 'loading',
				loading: true,
				lineLoading: true,
				user: {},
				keyword: "",
				userfilter: {},
				NodeId: "",
				FiberId: "",
				Addr: "",
				formState: {
					Length: ""
				},
				lineshow: false,
				modalshow: false,
				changeshow: false,
				laytypeshow: false,
				addlaytypeshow: false,
				region: "",
				changelength: "",
				changeidx: "",
				laytype: "",
				columns: [{
					name: '架空'
				}, {
					name: '直埋'
				}, {
					name: '管道'
				}],
				addFormState:{Length: ""},
				rules: {
					'Length': {
						required: true,
						transform(value) {
						    return String(value);
						},
						message: '请输入皮长',
						trigger: ['blur']
					},
				},
			}
		},
		onLoad(option) {
			this.user = JSON.parse(uni.getStorageSync("$userinfo"))
			this.NodeId = option.NodeId
			this.region = option.Region
		},
		onShow() {
			this.linefiberlistBynode = []
			this.getlist()
			this.choosenLine = getApp().globalData.choosenLine
			this.getLineFiberList()
		},
		onReady() {
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		    this.$refs.uForm.setRules(this.rules)
		    this.$refs.uForm1.setRules(this.rules)
		},
		methods: {
			openpage(e) {
				uni.navigateTo({
					// url: "lineequdetail?Id=" + e 
					url: `lineequdetail?NodeId=${this.NodeId}&Id=${e}`
				})
			},
			async getlist() {
				this.status = 'loading'
				// let querytype = this.$route.query.querytype
				let para = {
					Parameters: [],
				}
				para.Parameters.push({
					FieldName: "NodeId",
					ConditionalType: "Equal",
					FieldValue: this.NodeId
				})
				para.OrderBys = ['CreateTime desc']
				para.pageSize = this.pageSize
				para.pageIndex = this.pageIndex
				// if (querytype == "日志") {
				// }
				await getlinefibernode(para).then(res => {
					let data = res.data
					this.linefiberlistBynode.push(...data)
					this.total = res.count
					this.totalPage = Math.ceil(this.total / this.pageSize)
				})
				if (this.linefiberlistBynode.length < this.pageSize) {
					this.loading = false; //如果数据列表小于当前页数，就让加载标签消失
					this.status = 'nomore';
				} else {
					this.status = 'loadmore';
				}
			},
			scrolltolower() {
				// 如果当前页数大于等于总页数，状态修改为没有更多了，不再继续往下执行代码
				if (this.pageIndex >= this.totalPage) {
					this.status = 'nomore';
					return;
				};
				this.status = 'loading'; //状态改为加载中
				this.pageIndex = ++this.pageIndex; //页面新增一页
				this.getlist(); //修改页数后，重新获取数据
			},
			async searchlist() {
				this.linefiberlistBynode = [] //初始化
				this.pageIndex = 1 //初始化当前页数为1
				this.loading = true
				await this.getlist()
			},
			gotoconnect() {
				this.lineshow = true
			},
			toaddfiber() {
				uni.navigateTo({
					url: 'addlinefiber'
				})
			},
			tochange(item) {
				this.changeshow = true;
				this.FiberId = item.FiberId
				this.formState = item
				// this.formState.Id = item.Id
				// this.formState.Length = item.Length
				// this.formState.LayType = item.LayType
				// this.formState.Idx = item.Idx		
			},
			connect() {
				this.$refs.uForm.validate().then(res => {
						let para = {
							fiberId: this.FiberId,
							nodeId: this.NodeId,
							length: this.addFormState.Length,
							layType: this.laytype
						}
						addFiberNode("", para).then(res => {
							if (res.code == 0) {
								this.$refs.uToast.show({
									message: res.message,
									type: 'success',
									position: 'top',
									duration: 1500
								})
								this.linefiberlistBynode = []
								this.getlist()
								this.addFormState.Length = ""
								this.lineshow = false
								this.modalshow = false
						
							} else {
								this.$refs.uToast.show({
									message: res.message,
									type: 'error',
									position: 'top',
									duration: 1500
								})
							}
						})
					}).catch(errors => {
						uni.$u.toast('请填写必填参数！')
					})		
			},
			delconnect() {
				delFiberNode(this.FiberId, this.NodeId).then(res => {
					if (res > 0) {
						this.$refs.uToast.show({
							message: '删除成功',
							type: 'success',
							position: 'top',
							duration: 1500
						})
						this.changeshow = false
						this.linefiberlistBynode = []
						this.getlist()
					} else {
						this.$refs.uToast.show({
							message: '删除失败,该缆线上不存在此节点',
							type: 'error',
							position: 'top',
							duration: 1500
						})
					}
				})
			},
			changeinfo() {
				this.$refs.uForm1.validate().then(res => {
						fiberNodeUpdate(this.formState).then(res => {
							if (res === true) {
								this.changeshow = false;
								this.linefiberlistBynode = []
								this.getlist()
							} else {
								this.$refs.uToast.show({
									message: '出错！',
									type: 'error',
									position: 'top',
									duration: 1500
								})
							}
						})
					}).catch(errors => {
						uni.$u.toast('请填写必填参数！')
					})			
			},
			changelaytype(e) {
				this.formState.LayType = e.name
			},
			tochangelaytype(e) {
				this.laytype = e.name
			},
			del(Id){
				let ids = []
				ids.push(Id)
				deleteLinefiber(ids).then((res) => {
					this.getLineFiberList()
				})			
			},
			tochoose(FiberId){
				this.choosenLine.push(FiberId)
				getApp().globalData.choosenLine = this.choosenLine
				// setTimeout(this.getLineFiberList,300)
			},
			delchoose(FiberId){
				let index = this.choosenLine.indexOf(FiberId);
				this.choosenLine.splice(index, 1);
				// setTimeout(this.getLineFiberList,300)
			},
			async getLineFiberList(){
				this.linefiberlist = []
				let para = {
					Parameters: [],
					OrderBys: ['CreateTime desc'],
					pageSize: this.linePageSize,
					pageIndex: this.linePageIndex
				}
				await this.choosenLine.forEach(e => {
					var paraById = {
						Parameters: [{
							FieldName: "Id",
							ConditionalType: "Equal",
							FieldValue: e
						}],
						OrderBys: ['CreateTime desc']
					}
					getlinefiber('', paraById).then(res => {
						res.data[0].Name = res.data[0].Name + '(已选中)'
						this.linefiberlist = this.linefiberlist.concat(res.data)
					})
				})
				await getlinefiber(this.region, para).then(res => {
					this.linefiberlist = this.linefiberlist.concat(res.data)
					this.lineTotal = res.count
					this.lineTotalPage = Math.ceil(this.lineTotal / this.linePageSize)
					if (this.linefiberlist.length < this.linePageSize) {
						this.lineloading = false; //如果数据列表小于当前页数，就让加载标签消失
						this.lineStatus = 'nomore';
					} else {
						this.lineStatus = 'loadmore';
					}
				})
			},
			scrolltolowerLine(){
				if (this.linePageIndex >= this.lineTotalPage) {
					this.lineStatus = 'nomore';
					return;
				};
				this.lineStatus = 'loading'; //状态改为加载中
				this.linePageIndex = ++this.linePageIndex; //页面新增一页
				let para = {
					Parameters: [],
					OrderBys: ['CreateTime desc'],
					pageSize: this.linePageSize,
					pageIndex: this.linePageIndex
				}
				getlinefiber(this.region,para).then(res => {
					this.linefiberlist = this.linefiberlist.concat(res.data)
					this.lineTotal = res.count
					this.lineTotalPage = Math.ceil(this.lineTotal / this.linePageSize)
				}); //修改页数后，重新获取数据
			},
			toconnect(e){
				uni.navigateTo({
					url: `lineconnect?nodeId=${e.NodeId}&equId=${e.FiberId}&equType=缆线`
				})
			},
			toshowLine(e){
				let pages = getCurrentPages() // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
				   let prevPage = pages[pages.length - 2] //上一页页面实例
				   uni.navigateBack({
				     delta:1,
				     success:() => {
				        prevPage.$vm.toshowLine(e) // 给上一页绑定方法otherFun,传参地址id
				     }
				   })
			}
		},
	}
</script>

<style>

</style>